package com.yc.web.servlets;

import com.yc.bean.Menu;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

@WebServlet("/admin/menu.action")
public class MenuServlet extends BaseServlet{
    public void getMyMenu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException {
        // 查询顶级菜单
        String sql = "SELECT * FROM menu WHERE parent_id IS NULL";
        List<Menu> topLevelMenus = db.select(Menu.class, sql);

        // 为每个顶级菜单递归获取子菜单
        for (Menu menu : topLevelMenus) {
            List<Menu> subMenus = retrieveSubMenus(menu.getId());
            menu.setChildren(subMenus); // 假设 Menu 类有一个设置子菜单的方法
        }

        // 将完整菜单结构转换为 JSON 并写入响应
        super.writeObiectJson(topLevelMenus, resp);
    }
    private List<Menu> retrieveSubMenus(int parentId) throws InvocationTargetException, InstantiationException, IllegalAccessException {
        String sql = "SELECT * FROM menu WHERE parent_id = ?";
        return db.select(Menu.class, sql, parentId);
    }

}
